package com.gelingqin.es.springbootdemo.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Map;
import java.util.Properties;
import com.gelingqin.es.springbootdemo.util.StringHelper;
import httl.Engine;
import httl.Template;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * next template engin 实现类
 * 
 * @author fish
 * @date 2019年10月29日
 */
@Service
public class NteService {

  private Engine engine;
  private String rootDir="template/";


  @PostConstruct
  public void init() {
    Properties init = new Properties();
    //init.put("compiler", "httl.spi.compilers.JavassistCompiler");
    init.put("template.directory","template/");
    init.put("reloadable",  "true");
    engine = Engine.getEngine(init);


  }

  public String read(String name, Map<String, Object> context) {
    try {
      Template template = engine.getTemplate(rootDir+name);
      return (String) template.evaluate(context);
    } catch (IOException e) {
      throw  new RuntimeException("读取失败");
    } catch (ParseException e) {
      throw  new RuntimeException("读取失败");
    }
  }

  public byte[] readBytes(String name, Map<String, Object> context) {
    String string = read(name, context);
    try {
      return string.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
      throw  new RuntimeException("读取失败");
    }
  }

}
